<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2022/12/8
 * Time: 9:40
 */

namespace app\controller;
use app\model\Product;
use PhpOffice\PhpSpreadsheet\IOFactory;

class Upload
{
    public function image(){
        $image = input('image');
        if (!empty($image)){
            $image = explode(',',$image)[1];
            $image = base64_decode($image);
            !is_dir('goods') && mkdir('goods');
            !is_dir('goods/attr') && mkdir('goods/attr');
            !is_dir('goods/attr/'.date('Ymd')) && mkdir('goods/attr/'.date('Ymd'));
            $file = 'goods/attr/'.date('Ymd').'/'.time().'.jpg';
            file_put_contents($file,$image);
            return json(['code' => 200,'msg' => '','data' =>  '/'.$file]);
        } else {
            $file = request()->file('file');
            // 上传到本地服务器
            $savename = \think\facade\Filesystem::putFile('topic', $file, 'public');
            $savename = str_replace('\\', '/', $savename);
            return json(['code' => 200,'msg' => '','data' =>  '/storage/'.$savename]);
        }
    }

    public function xlsx($type = 0,$user_id = 0){
        $target_dir = "uploads/"; // 指定上传文件的目录
//        dd($_FILES);
        $target_file = $_FILES['file']["tmp_name"]; // 获取上传文件的完整路径
        $file_name = $_FILES['file']["name"];
        $validExtensions = ['xlsx', 'xlx'];
        // 允许特定格式的文件上传
        if (!isValidFileExtension($file_name, $validExtensions))
            return json(['code' => 400,'msg' => '文件后缀错误必须是xlx,xlsx','data' => []],200);
        // 检查文件是否已经存在
//        if (file_exists($target_file)) {
//            echo "对不起，文件已经存在。";
//            $uploadOk = 0;
//        }
        // 检查文件大小（这里限制为 512MB）
        if ($_FILES["file"]["size"] > 512000000)
            return json(['code' => 400,'msg' => '文件不得大于512MB','data' => []],200);
        // 检查 $uploadOk 是否为 0，如果是，则文件上传失败
        if (move_uploaded_file($target_file, $target_dir.'/'.$file_name)){
            // 指定XLSX文件的路径
            $filePath = $target_dir.'/'.$file_name;
            // 加载XLSX文件
            $spreadsheet = IOFactory::load($filePath);
            // 获取第一个工作表
            $worksheet = $spreadsheet->getActiveSheet();
            // 获取最高行数和列数
            $highestRow = $worksheet->getHighestRow();
            $highestColumn = $worksheet->getHighestColumn();
            // 遍历每一行数据
            $type_array = [
                1 => ['A','B','C','D','E','F','G','H','I','J','K','L'],
                2 => ['A','B','C','D'],
                3 => ['A','B','C','D','E','F','G']
            ];
            $i = 0;
            for ($row = 1; $row <= $highestRow; $row++) {
                // 获取当前行的数据
                $rowData[$i] = [];
                foreach ($type_array[$type] AS $key => $value) {
                    $cell = $worksheet->getCell($value . $row);
                    $value = $cell->getValue();
                    $rowData[$i][] = $value;
                }
                // 输出或处理行数据
                $i++;
            }
            if (empty($rowData[0]))
                return json(['code' => 400,'msg' => '表格格式错误'],200);
            foreach ($rowData AS $key => $value){
                if ($key == 0)continue;
                if ($type == 1){
                    if (empty($value[0]))continue;
                    $install[] = [
                        'name' => $value[0],
                        'weight' => $value[2],
                        'model' => $value[3],
                        'attr' => $value[1],
                        'is_tax' => $value[4] == '是' ? 1:0,
                        'material' => $value[5],
                        'material_attr' => $value[6],
                        'external_diameter' => $value[7],
                        'external_diameter_deviation' => $value[8],
                        'internal_diameter' => $value[9],
                        'internal_diameter_deviation' => $value[10],
                        'thickness' => $value[11],
                        'user_id' => $user_id
                    ];
                }elseif($type == 2){
                    
                }
            }
            if(!empty($install)) {
                if($type == 1) (new Product())->saveAll($install);
            }
        }else{
            return json(['code' => 200,'msg' => '','data' => []],200);
        }
        return json(['code' => 200,'msg' => '','data' => []],200);
    }
}